package com.gzz.boot.sequence;

import org.springframework.data.redis.core.RedisTemplate;

import java.util.Random;
import java.util.UUID;

public class RedisSegGenerator {

    private RedisTemplate<String, Long> redisTemplate;
    /**
     * 获取唯一Id
     * @param key
     * @param hashKey
     * @param delta 增加量（不传采用1）
     * @return
     */
    public Long GenOnlyKey(String key,String hashKey,Long delta){
        try {
            if (null == delta) {
                delta=1L;
            }
            return redisTemplate.opsForHash().increment(key, hashKey, delta);
        } catch (Exception e) {//redis宕机时采用uuid的方式生成唯一id
            int first = new Random(10).nextInt(8) + 1;
            int randNo= UUID.randomUUID().toString().hashCode();
            if (randNo < 0) {
                randNo=-randNo;
            }
            return Long.valueOf(first + String.format("%16d", randNo));
        }
    }
}
